const https = require("https")
const fs = require("fs")
const fsPromise = require("fs/promises")
const path = require("path")

const baseUrl = 'https://static.arcgis.com/fonts'

const fontFamilyConfig = [
    "arial-unicode-ms",
    "noto-serif",
    "Playfair Display",
    "Microsoft YaHei",
    "SimSun"
]

const saveDir = path.resolve(__dirname, "./fonts")


// 发起请求
function doRequest(url) {
    return new Promise((resolve, reject) => {
        https.get(url, res => {
            res.on("data", (data) => {
                resolve(data)
            })
        }).on("error", err => {
            reject(err)
        })
    })
}

// 数据写入文件
function saveDataToFile(filePath, data) {
    let pathResult = path.parse(filePath)

    fs.mkdir(pathResult.dir, { recursive: true }, err => {
        if (err) {
            console.log("create dir error", err)
            return
        }

        fs.access(filePath, err => {
            // 文件不存在
            if (err) {
                // 写入文件
                fs.writeFile(filePath, data, (err) => {
                    if (err) throw err;
                    console.log('save file success');
                })
            }
        })
    })
}


const queue = [];
let familys = fontFamilyConfig.map(item => item.toLowerCase().replace(" ", "-"))

familys.forEach(f => {
    let normal = `${f}-regular`
    let bold = `${f}-bold`
    loopFileFamily(normal)
    loopFileFamily(bold)
})


function loopFileFamily(family) {
    let familyDir = path.resolve(saveDir, `./${family}`)
    for (let i = 0; i < 257; i++) {
        let start = i * 256;
        let end = (i + 1) * 256 - 1;

        let name = `${start}-${end}`

        let filePath = path.format({
            dir: familyDir,
            name: name,
            ext: '.pbf'
        })
        let url = `${baseUrl}/${family}/${name}.pbf`;
        queue.push({
            url,
            filePath,
            fn: requestItem(url, filePath)
        })
    }
}

function flush() {
    queue.forEach(item => {
        item.fn()
    })
}

flush()


function requestItem(url, filepath) {
    return (fn) => {
        // 判断是否存在
        fs.access(filepath, fs.constants.F_OK, err => {
            // 不存在
            if(err) {
                doRequest(url).then(res => {
                    saveDataToFile(filepath, res, fn)
                })
            }
        })
    }
}



